
package org.winexpress

import org.codehaus.groovy.grails.web.json.JSONObject;
import org.codehaus.groovy.grails.web.json.JSONArray;
import grails.converters.JSON


/**
 *
 * @author Swee Zhi
 */
class CountryManagement {
    
    def listCountries() {
        def countries = Country.list()
        JSONArray arr = new JSONArray()
        countries.each() {
            JSONObject obj = new JSONObject()
            obj.put("id",it.id)
            obj.put("countryName",it.countryName)
            arr.add(obj)
        }
        
        return arr
    }
    
    def getCountryByID(id) {
        def c = Country.findById(id)
        JSONObject obj = new JSONObject()
        obj.put("id",c.id)
        obj.put("countryName",c.countryName)
        println "country test: " + c.id
        
        return obj
    }
    
    def getCountryByCountryName(countryName) {
        def Country = Country.findByCountryName(countryName)
        JSONObject obj = new JSONObject()
        obj.put("id",Country.id)
        obj.put("countryName",Country.countryName)
        
        return obj
    }
    
//    def getCountryForDbByCountryName(countryName) {
//        def c = Country.findByCountryName(countryName)
//        
//        return c
//    }
    
    def addCountry(countryName,description) {
        def status
        
        Country c = new Country()
        c.countryName = countryName
        if (c.save()) {
            status = true
        }
        else {
            status = false
        }
        println 'Management >> Add Country >> ' + status
        
        return status
    }
    
    def updateCountry(country) {
        def status
        
        Country c = Country.findById(country.id)
        if (country.has("countryName")) { c.countryName = country.countryName }
        if (c.save(flush:true)) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Update Country >> ' + status
        
        return status
    }
    
    def deleteCountry(id) {
        def status
        
        Country c = Country.findById(id)
        if (c.delete()) {
            status = true
        }
        else {
            status = false
        }        
        println 'Management >> Delete Country >> ' + status
        
        return status
    }
}

